package com.scujj.cs6.job;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scujj.cs6.constant.WeatherConstant;
import com.scujj.cs6.model.vo.RealTimeDataVo;
import com.scujj.cs6.model.vo.WeatherNowVo;
import com.scujj.cs6.service.WeatherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class WeatherLocalScheduleJob {

    private final WeatherService weatherService;

    private final StringRedisTemplate redisTemplate;

    private final ObjectMapper mapper;


    @Scheduled(cron = "0 0 * * * ?")
    public void syncWeatherLocalData() {
        List<WeatherNowVo> weatherNowVos = weatherService.fetchCapitalCitiesLocalWeather();
        RealTimeDataVo<List<WeatherNowVo>> realTimeDataVo = new RealTimeDataVo<>();
        realTimeDataVo.setData(weatherNowVos);
        realTimeDataVo.setUpdateTime(LocalDateTime.now());
        String key = WeatherConstant.localCacheKeyPrefix + "all";
        String json;
        try {
            json = mapper.writeValueAsString(realTimeDataVo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("定时任务：同步省会城市天气今日json信息写入到数据库: {}",json);
        redisTemplate.opsForValue().set(key, json, Duration.ofHours(1));
    }
}
